<template>
  <scroll-view
    scroll-y
    class="scroll-view"
    @scrolltolower="scrolltolower"
    refresher-enabled
    :refresher-triggered="trigger"
    @refresherrefresh="onRefresherrefresh"
  >
    <!-- 已登录: 显示购物车 -->
    <template v-if="isLogin">
      <!-- 购物车列表 -->
      <view class="cart-list" v-if="cartList.length > 0">
        <!-- 优惠提示 -->
        <view class="tips">
          <text class="label">满减</text>
          <text class="desc">满1件, 即可享受9折优惠</text>
        </view>
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <uni-swipe-action-item v-for="item in cartList" :key="item.skuId" class="cart-swipe">
            <!-- 商品信息 -->
            <view class="goods">
              <!-- 选中状态 -->
              <text
                class="checkbox"
                :class="{ checked: item.selected }"
                @click="changeChecked(item)"
              ></text>
              <navigator
                :url="`/pages/goodsDetail/goodsDetail?id=${item.id}`"
                hover-class="none"
                class="navigator"
              >
                <image mode="aspectFill" class="picture" :src="item.picture"></image>
                <view class="meta">
                  <view class="name ellipsis">{{ item.name }}</view>
                  <view class="attrsText ellipsis">{{ item.attrsText.split('，').join(' ') }}</view>
                  <view class="price">{{ item.nowPrice }}</view>
                </view>
              </navigator>
              <!-- 商品数量 -->
              <view class="count">
                <text class="text" @click="reduceCount(item)">-</text>
                <input
                  class="input"
                  type="number"
                  v-model="item.count"
                  @change="changeCount(item)"
                />
                <text class="text" @click="addCount(item)">+</text>
              </view>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <button class="button delete-button" @click="deleteGoods(item.skuId)">删除</button>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <!-- 购物车空状态 -->
      <view class="cart-blank" v-else>
        <image src="../../static/images/blank_cart.png" class="image" />
        <text class="text">购物车还是空的，快来挑选好货吧</text>
        <navigator open-type="switchTab" url="/pages/index/index" hover-class="none">
          <button class="button">去首页看看</button>
        </navigator>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view class="login-blank" v-else>
      <text class="text">登录后可查看购物车中的商品</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
    <!-- 猜你喜欢 -->
    <tphGuess ref="tphGuessRef"></tphGuess>
    <!-- 底部占位空盒子 -->
    <view class="toolbar-height"></view>
  </scroll-view>
  <!-- 吸底工具栏 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <text class="all" :class="{ checked: allChecked }" @click="changeAllChecked">全选</text>
    <text class="text">合计:</text>
    <text class="amount">{{ allPrice }}</text>
    <view class="button-grounp">
      <view
        class="button payment-button"
        :class="{ disabled: selectedGoodsNum === 0 }"
        @click="goBuy"
      >
        去结算({{ selectedGoodsNum }})
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
// 引入仓库
import { useUserStore } from '@/store/modules/user'
// 引入接口函数
import {
  getCartListAPI,
  putCartGoodAPI,
  putCartGoodsAllSelectedAPI,
  deleteCartGoodsAPI,
} from '@/api/cart'
// 引入ts类型
import type { cartInfoType } from '@/types/cart'
import { onShow } from '@dcloudio/uni-app'
// 创建pinia对象
const userStore = useUserStore()
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 计算出用户是否已登录
const isLogin = computed(() => {
  return userStore.token
})
// 购物车列表
const cartList = ref<cartInfoType[]>([] as cartInfoType[])
// 获取购物车列表数据的函数
const getCartList = async () => {
  const res = await getCartListAPI()
  if (res.code === '1') {
    cartList.value = res.result
  }
}
// 计算出全选按钮的选中状态
const allChecked = computed(() => {
  return cartList.value.every((item) => item.selected)
})
// 切换商品选中状态
const changeChecked = async (goods: cartInfoType) => {
  goods.selected = !goods.selected
  // 调用接口
  await putCartGoodAPI(goods.skuId, { selected: goods.selected })
}
// 减少商品个数
const reduceCount = async (goods: cartInfoType) => {
  if (goods.count > 1) {
    goods.count--
    // 发送请求
    await putCartGoodAPI(goods.skuId, { count: goods.count })
  }
}
// 增加商品个数
const addCount = async (goods: cartInfoType) => {
  if (goods.count < goods.stock) {
    goods.count++
    // 发送请求
    await putCartGoodAPI(goods.skuId, { count: goods.count })
  }
}
// 全选按钮的回调
const changeAllChecked = async () => {
  const selected = allChecked.value
  cartList.value.forEach((item) => {
    item.selected = !selected
  })
  // 调用接口
  await putCartGoodsAllSelectedAPI(!selected)
}
// 数量文本框修改的回调
const changeCount = async (goods: cartInfoType) => {
  // 不能小于1
  if (goods.count < 1) {
    goods.count = 1
  } else if (goods.count > goods.stock) {
    // 不能超过村库存
    goods.count = goods.stock
  } else {
    goods.count = Math.trunc(goods.count)
  }
  // 发送请求
  await putCartGoodAPI(goods.skuId, { count: goods.count })
}
// 计算出总金额
const allPrice = computed(() => {
  let num = 0
  const arr = cartList.value.filter((item) => item.selected)
  arr.forEach((item) => {
    num += item.count * Number(item.nowPrice)
  })
  return num
})
// 计算出选择的商品个数
const selectedGoodsNum = computed(() => {
  return cartList.value.filter((item) => item.selected).length
})
// 点击结算按钮的回调
const goBuy = () => {
  // 未选中商品，不让跳转
  if (selectedGoodsNum.value < 1) {
    return
  }
  // 跳转到填写订单页
  uni.navigateTo({
    url: '/pagesOrder/create/create',
  })
}
// 删除按钮的回调
const deleteGoods = (id: string) => {
  uni.showModal({
    content: '是否确认删除?',
    success: async (res) => {
      if (res.confirm) {
        // 确认删除，调用接口
        await deleteCartGoodsAPI([id])
        // 提示用户删除成功
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          mask: true,
        })
        // 删除成功，重新获取购物车商品
        getCartList()
      } else {
        console.log('取消')
      }
    },
  })
}
// 猜你喜欢组件的ref对象
const tphGuessRef = ref()
// 滚动到底触发的回调
const scrolltolower = () => {
  tphGuessRef.value.scrolltolower()
}
// 下拉刷新状态
const trigger = ref(false)
// 下拉刷新
const onRefresherrefresh = async () => {
  trigger.value = true
  // 重置猜你喜欢模块的数据
  tphGuessRef.value?.resetData()
  // 重新获取购物车数据跟重置猜你喜欢数据
  await Promise.all([getCartList(), tphGuessRef.value?.getGuessData()])
  // 将下拉刷新关闭
  trigger.value = false
}
onShow(() => {
  getCartList()
})
</script>

<style lang="scss">
/* #ifdef APP-PLUS || H5 */
 page {
  display: flex;
  height: 100%
}
/* #endif */

// 根元素
:host {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f7f7f8;
}

// 滚动容器
.scroll-view {
  flex: 1;
  overflow-y: scroll;
}

// 购物车列表
.cart-list {
  padding: 0 20rpx;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;

    .label {
      color: #fff;
      padding: 7rpx 15rpx 5rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
      background-color: #ff0344;
      margin-right: 10rpx;
    }
  }

  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 20rpx 20rpx 80rpx;
    border-radius: 10rpx;
    background-color: #fff;
    position: relative;

    .navigator {
      display: flex;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 100%;

      &::before {
        content: '\e633';
        font-family: 'iconfont' !important;
        font-size: 40rpx;
        color: #444;
      }

      &.checked::before {
        content: '\e6c1';
        color: #ff0344;
      }
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      height: 72rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      line-height: 1.8;
      padding: 0 15rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      line-height: 1;
      font-size: 26rpx;
      color: #444;
      margin-bottom: 2rpx;
      color: #cf4444;

      &::before {
        content: '￥';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 20rpx;
      right: 5rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 220rpx;
      height: 48rpx;

      .text {
        height: 100%;
        padding: 0 20rpx;
        font-size: 32rpx;
        color: #444;
      }

      .input {
        height: 100%;
        text-align: center;
        border-radius: 4rpx;
        font-size: 24rpx;
        color: #444;
        background-color: #f6f6f6;
      }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: #cf4444;
    }
  }
}

// 空状态
.cart-blank,
.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 60vh;
  .image {
    width: 270rpx;
    height: 256rpx;
  }
  .text {
    color: #444;
    font-size: 26rpx;
    margin: 20rpx 0;
  }
  .button {
    width: 240rpx !important;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: #ff0344;
  }
}

// 吸底工具栏
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: var(--window-bottom);
  z-index: 1;
  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .all {
    margin-left: 25rpx;
    font-size: 14px;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'iconfont' !important;
    content: '\e633';
    font-size: 40rpx;
    margin-right: 8rpx;
  }

  .checked::before {
    content: '\e6c1';
    color: #ff0344;
  }

  .text {
    margin-right: 8rpx;
    margin-left: 32rpx;
    color: #444;
    font-size: 14px;
  }

  .amount {
    font-size: 20px;
    color: #cf4444;

    .decimal {
      font-size: 12px;
    }

    &::before {
      content: '￥';
      font-size: 12px;
    }
  }

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 13px;
    color: #fff;

    .button {
      width: 240rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background-color: #ff0344;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}
// 底部占位空盒子
.toolbar-height {
  height: 100rpx;
}
</style>
